<template>
    <div class="bond-trading-form">
        <el-row class="form-row">
            <el-col :span="12">
                <el-form-item label="价格模式:">
                    <el-select v-model="riskOrderForm.orderPriceType" size="mini">
                        <el-option v-for="i in investPriceSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="投资类型:">
                    <el-select v-model="riskOrderForm.investType" size="mini">
                        <el-option v-for="i in investTypeSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row class="form-row">
            <el-col :span="12">
                <el-form-item label="指令用途:">
                    <el-select v-model="riskOrderForm.orderPurpose" size="mini">
                        <el-option v-for="i in orderPurposeSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="指令优先级:">
                    <el-select v-model="riskOrderForm.orderLevel" size="mini">
                        <el-option v-for="i in orderLevelSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row class="form-row" v-if="show">
            <el-col>
                <el-form-item label="证券代码:">
                    <el-select
                        v-model="riskOrderForm.stockCode"
                        @change="getOrdersDirection"
                        filterable
                        remote
                        :remote-method="searchStockCodeList"
                        :loading="selectLoading"
                        style="width: 100%"
                        size="mini"
                    >
                        <el-option
                            v-for="i in stockCodeSelectData"
                            :key="i.stockCode"
                            :label="i.stockCode + ' ' + i.stockNameSt"
                            :value="i.stockCode"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row class="form-row">
            <el-col :span="12">
                <el-form-item label="订单方向:">
                    <el-select v-model="riskOrderForm.orderDirection" size="mini" :class="['font-color-' + textColor]">
                        <el-option v-for="i in orderDirectionSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="指令价格:"
                    ><el-input-number
                        v-model="riskOrderForm.orderPrice"
                        @change="getOrderBalance"
                        :precision="2"
                        :min="0"
                        controls-position="right"
                        size="mini"
                        :class="[textColor ? 'font-color-' + textColor : '']"
                    ></el-input-number
                ></el-form-item>
            </el-col>
        </el-row>
        <el-row class="form-row">
            <el-col :span="12">
                <el-form-item label="指令数量:"
                    ><el-input-number
                        v-model="riskOrderForm.orderAmount"
                        @change="getOrderBalance"
                        :min="0"
                        controls-position="right"
                        size="mini"
                        :class="[textColor ? 'font-color-' + textColor : '']"
                    ></el-input-number
                ></el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="指令金额:">
                    <el-tooltip v-if="riskOrderForm.orderBalance" placement="top" :content="computedorderBalanceChinese">
                        <el-input-number
                            v-model="riskOrderForm.orderBalance"
                            :precision="2"
                            :min="0"
                            controls-position="right"
                            size="mini"
                            :class="[textColor ? 'font-color-' + textColor : '']"
                        ></el-input-number>
                    </el-tooltip>
                    <el-input-number
                        v-else
                        v-model="riskOrderForm.orderBalance"
                        :precision="2"
                        :min="0"
                        controls-position="right"
                        size="mini"
                        :class="[textColor ? 'font-color-' + textColor : '']"
                    ></el-input-number>
                </el-form-item>
            </el-col>
        </el-row>
        <el-divider></el-divider>
        <el-row class="form-row">
            <el-col :span="12">
                <el-form-item label="清算速度:">
                    <el-select v-model="riskOrderForm.clearSpeed" size="mini" :class="['font-color-' + textColor]">
                        <el-option v-for="i in clearSpeedSelectData" :key="i.dictKey" :label="i.dictKeyName" :value="i.dictKey"> </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="回购天数:">
                    <el-input-number
                        v-model="riskOrderForm.repoDay"
                        :min="0"
                        controls-position="right"
                        size="mini"
                        @change="handleRepoDayChange"
                    ></el-input-number>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row class="form-row">
            <el-col :span="12">
                <el-form-item label="首次交割日:"
                    ><el-date-picker
                        v-model="riskOrderForm.firstSettleDate"
                        type="date"
                        format="yyyyMMdd"
                        value-format="yyyyMMdd"
                        size="mini"
                        style="width: 100%"
                        placeholder="请选择"
                    ></el-date-picker
                ></el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="到期交割日:"
                    ><el-date-picker
                        v-model="riskOrderForm.endSettleDate"
                        type="date"
                        format="yyyyMMdd"
                        value-format="yyyyMMdd"
                        size="mini"
                        placeholder="请选择"
                        style="width: 100%"
                        @change="handleEndSettleDateChange"
                    ></el-date-picker
                ></el-form-item>
            </el-col>
        </el-row>
        <el-row class="form-row">
            <el-col :span="12">
                <el-form-item label="交易对手序号:">
                    <el-select v-model="riskOrderForm.opponentCode" size="mini" filterable remote :remote-method="getOpponentCode">
                        <el-option v-for="i in opponentCodeSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
            <el-col :span="12">
                <el-form-item label="对手交易员号:">
                    <el-input :value="riskOrderForm.opponentTraderCode" size="mini"></el-input>
                </el-form-item>
            </el-col>
        </el-row>
        <el-row class="form-row">
            <el-col :span="12">
                <el-form-item label="撤单类型:">
                    <el-select v-model="riskOrderForm.cancelType" size="mini">
                        <el-option v-for="i in cancelTypeSelectData" :key="i.dictKey" :label="i.dictKey + ' ' + i.dictKeyName" :value="i.dictKey">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-col>
        </el-row>
    </div>
</template>
<script lang="ts">
import Invest from '@/common/dict/invest';
import { objToArr, SGU_CACHE } from '@/utils/diction-const-util';
import { NumberToWords, highlightColor } from '@/utils/tools';
import { getUser } from '@/utils/user-util';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import XEUtils from 'xe-utils';
import moment from 'moment';

@Component({
    name: 'RepurchaseOrder',
})
export default class RepurchaseOrder extends Vue {
    @Prop()
    show: boolean;
    private riskOrderForm = {
        orderPriceType: '1',
        orderUser: getUser().userCode,
        orderPurpose: '1',
        investType: '1',
        stockCode: '',
        marketCode: '',
        orderDirection: '',
        orderPrice: undefined,
        orderAmount: undefined,
        orderBalance: undefined,
        orderLevel: '1',
        opponentCode: '',
        opponentTraderCode: '',
        firstSettleDate: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        endSettleDate: XEUtils.toDateString(new Date(), 'yyyyMMdd'),
        clearSpeed: '0',
        settleType: '1',
        repoDay: undefined,
        bondYield: '',
        interest: '0',
        cancelType: '3',
        stockType: '',
        reportCode: '',
    };
    Invest: any = new Invest();

    investPriceSelectData: any[] = []; // 价格模式下拉框数据

    investTypeSelectData: any[] = []; // 投资类型下拉框数据

    orderPurposeSelectData: any[] = []; // 指令用途下拉框数据

    orderLevelSelectData: any[] = []; // 指令优先级下拉框数据

    stockCodeSelectData: any[] = []; // 证券代码下拉框数据

    allStockType: any[] = [];

    allOrderDirection: any[] = []; // 所有订单方向数据

    orderDirectionSelectData: any[] = []; // 订单方向下拉框数据

    cancelTypeSelectData: any[] = []; // 撤单类型下拉框数据

    selectLoading: boolean = false; // 下拉框远程搜索时的加载状态

    opponentCodeSelectData: any[] = []; // 交易对手方下拉数据

    tradeDays: any[] = [];

    textColor: string = ''; // 红绿凸显

    // 证券代码下拉框数据相关
    stockCodeMsg = {
        url: '/original/stock/list',
        submit: {
            paging: { total: 0, currentPage: 1, totalPage: 0, pageSize: 20 },
            multStockType: ['-', '8', 'I'],
            multMarketCode: ['1', '2', '5'],
            stockCode: '',
        },
    };

    stockInfoPojo: any = {};
    clearSpeedSelectData: any[] = []; // 清算速度下拉数据

    @Watch('riskOrderForm', { immediate: true, deep: true })
    private getForm() {
        this.$emit('getRiskForm', this.riskOrderForm);
    }

    @Watch('stockInfoPojo', { immediate: true, deep: true })
    private getStockName() {
        this.$emit('getStockName', this.stockInfoPojo);
    }

    /**
     * 判断字段颜色
     */
    @Watch('riskOrderForm', { immediate: true, deep: true })
    handleFieldColor() {
        if (['1', '3', '5', 'J', 'K', 'RZZY', 'U', 'V', 'Y'].includes(this.riskOrderForm.orderDirection)) {
            this.textColor = highlightColor()[1];
        } else if (['2', '4', '6', 'L', 'RQZY', 'T', 'W', 'X'].includes(this.riskOrderForm.orderDirection)) {
            this.textColor = highlightColor()[2];
        } else {
            this.textColor = highlightColor()[0];
        }
    }

    async mounted() {
        // 获取价格模式下拉框数据
        this.investPriceSelectData = await SGU_CACHE('PriceType', '/dict/list/code/Y_000237', []);
        // 获取投资类型下拉框数据
        this.investTypeSelectData = objToArr(this.Invest.investType);
        // 获取指令用途下拉框数据
        this.orderPurposeSelectData = objToArr(Invest.investPurpose);
        // 获取指令优先级下拉框数据
        this.orderLevelSelectData = objToArr(this.Invest.investLevel);
        // 获取证券代码下拉框数据
        this.getstockCodeList();
        // 获取清算速度下拉数据
        this.clearSpeedSelectData = objToArr(this.Invest.clearSpeed);
        // 交易日期获取 获取未来150天的交易日期
        this.getSystemTradeDay();

        // 获取所有证券类别 (用于筛选订单方向)
        this.allStockType = await SGU_CACHE('StockType', '/dict/stockType/list', []);
        // 获取所有订单方向
        this.allOrderDirection = await SGU_CACHE('TradeDirection', '/dict/tradeDirections', []);
        if (!this.show) {
            this.orderDirectionSelectData = this.allOrderDirection;
        }

        // 获取撤单类型下拉框数据
        this.cancelTypeSelectData = objToArr(this.Invest.CancelType);
        this.getOpponentCode('');
    }

    // 获取指令金额 = 指令价格 * 指令数量
    getOrderBalance() {
        this.riskOrderForm.orderBalance = (Number(this.riskOrderForm.orderPrice) * Number(this.riskOrderForm.orderAmount)).toString();
    }

    // 指令金额 大写中文
    get computedorderBalanceChinese() {
        return NumberToWords(this.riskOrderForm.orderBalance.toString());
    }

    //   获取交易对手方信息
    private getOpponentCode(value: string) {
        this.$axios
            .post('/dict/opponent/select', {
                dictKey: value,
                dictKeyName: value,
            })
            .then((res: any) => {
                this.opponentCodeSelectData = res;
            });
    }

    // 获取证券代码下拉框数据
    getstockCodeList() {
        this.selectLoading = true;
        this.$axios.post(this.stockCodeMsg.url, this.stockCodeMsg.submit).then((res: any) => {
            this.stockCodeSelectData = res.list || [];
            this.selectLoading = false;
        });
    }

    // 证券代码下拉框远程搜索
    searchStockCodeList(e: string) {
        this.stockCodeMsg.submit.stockCode = e;
        this.getstockCodeList();
    }

    // 根据证券类别获取订单方向
    private getOrdersDirection(e) {
        this.riskOrderForm.orderDirection = '';
        let stockType = null;
        for (let i = 0; i < this.stockCodeSelectData.length; i++) {
            const ele = this.stockCodeSelectData[i];
            if (ele.stockCode === e) {
                stockType = ele.stockType;
                this.riskOrderForm.marketCode = ele.marketCode;
                this.riskOrderForm.reportCode = ele.reportCode;
                this.riskOrderForm.stockType = ele.stockType;

                break;
            }
        }
        let st = this.stockCodeSelectData.find(item => item.stockCode === e);
        this.stockInfoPojo[e] = st.stockNameSt;
        let stockTypeE = this.allStockType.find(item => item.dictKey === stockType);
        if (stockTypeE && stockTypeE.param1) {
            this.orderDirectionSelectData = this.allOrderDirection.filter(item => stockTypeE.param1.includes(item.dictKey));
        }
    }

    /**
     * 到期日期计算公式
     */
    calcEndSettleDate(instruction) {
        if (Number(instruction.repoDay || 0) === 0) {
            return '';
        } else {
            return this.tradeDays.find(
                item =>
                    item >=
                    Number(
                        moment()
                            .add(Number(instruction.repoDay) + Number(instruction.clearSpeed), 'd')
                            .format('YYYYMMDD')
                    )
            );
        }
    }
    /**
     * 回购天数计算公式
     */
    calcRepoDay(instruction) {
        if (!instruction.endSettleDate) {
            return '';
        } else {
            return Math.ceil(
                moment(instruction.endSettleDate, 'YYYYMMDD').diff(moment().add(Number(instruction.clearSpeed), 'd'), 'seconds') / 3600 / 24
            );
        }
    }

    handleRepoDayChange(e) {
        let fundInfo = JSON.parse(JSON.stringify(this.riskOrderForm));
        fundInfo.repoDay = e;
        fundInfo.endSettleDate = this.calcEndSettleDate(fundInfo).toString();
        this.riskOrderForm = JSON.parse(JSON.stringify(fundInfo));
    }

    handleEndSettleDateChange(e) {
        let fundInfo = this.riskOrderForm;
        fundInfo.endSettleDate = e;
        fundInfo.repoDay = this.calcRepoDay(fundInfo);
        this.riskOrderForm = JSON.parse(JSON.stringify(fundInfo));
    }

    // 查询未来150天的交易日期
    getSystemTradeDay() {
        this.$axios.get('/baseInfomation/system/trade/day').then((res: any) => {
            this.tradeDays = res.map(item => Number(item)).sort((a, b) => a - b);
        });
    }
}
</script>
<style lang="scss" scoped>
.el-divider {
    margin: 0;
    margin-top: 5px;
}
.form-row {
    margin-top: 3px;
    .el-form-item--small {
        margin: 0;
        & /deep/ .el-form-item__label {
            color: #575757;
        }
        & /deep/ .el-input__inner {
            height: 28px;
            line-height: 28px;
        }
        .font-color-red {
            /deep/ input {
                color: red !important;
            }
            /deep/ .el-input-group__append {
                color: red !important;
            }
        }
        .font-color-green {
            /deep/ input {
                color: green !important;
            }
            /deep/ .el-input-group__append {
                color: green !important;
            }
        }
    }
}
</style>
